package com.cwt_taxi_xa.timer;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.cwt_taxi_xa.ActivityJJQ;
import com.cwt_taxi_xa.ActivityMain;
import com.cwt_taxi_xa.ActivityPower;
import com.cwt_taxi_xa.ActivityWaitQD;
import com.cwt_taxi_xa.CWTBaseActivity;
import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.ShowVersionInfo;
import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.constants.ConstantsState;
import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.data.DataUtil;
import com.cwt_taxi_xa.data.Vinfo;
import com.cwt_taxi_xa.data.carInfo;
import com.cwt_taxi_xa.data.loginfo;
import com.cwt_taxi_xa.model.AppInfo;
import com.cwt_taxi_xa.protocol.CardUtil;
import com.cwt_taxi_xa.protocol.DDUtil;
import com.cwt_taxi_xa.protocol.DeviceBiz;
import com.cwt_taxi_xa.protocol.MCUUtil;
import com.cwt_taxi_xa.protocol.MeterEncoder;
import com.cwt_taxi_xa.service.DvrService;
import com.cwt_taxi_xa.service.SerialPortService;
import com.cwt_taxi_xa.util.AppBiz;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.CatchLogUtils;
import com.cwt_taxi_xa.util.ExceptionUtil;
import com.cwt_taxi_xa.util.FileOper;
import com.cwt_taxi_xa.util.HttpUtils;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.StringParser;
import com.cwt_taxi_xa.util.SystemUtils;
import com.cwt_taxi_xa.util.ToastUtils;
import com.cwt_taxi_xa.util.Tools;
import com.cwt_taxi_xa.util.VersionBiz;
import com.cwt_taxi_xa.util.Zipper;
import com.google.gson.Gson;

import org.apache.http.HttpEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TimerCommon extends TimerTask {

	final String TAG = "TimerCommon";

	public static String lastSendDVRV = "null";
	public static String DVRV = "null";

	public static String lastSendMcuV = "null";
	public static int lastSendAppV = 0;

	int count_checkNet = 1;
	int count_checkMCU = 150;
	int count_checkDVR = 150;
	int count_volBg = 15;
	public static int count_ddtime = 0;
	public static int count_maskCheck = 0;//口罩检查
	public static int count_vUp = 10*60;
	int count_232 = 100;
	int count_sendInfo = 0;

	int count_bmd = 0;

	ConnectivityManager manager = null;
	NetworkInfo networkinfo = null;

	MediaPlayer mMediaPlayer;

	static int isfirstVol = 1;

	public static long lastReTime = 0;


	private int count_checkCPU = 0;
	private int count_checkCPUTemp = 0;
	int count_checkLog = 0;
	int count_checkDvrState = 0;
	int count_checkMemory = 0;

	@Override
	public void run() {

		lastReTime = System.currentTimeMillis();


		AppLog.savelog("线程问题：0-线程开始："+lastReTime);
		AppLog.savelog("线程问题：1-网络检查1");
		/**
		 * 网络检查
		 */
		if (count_checkNet > 1) {
			count_checkNet = 0;
			try {
				if(manager==null){
					if(MainApplication.topActivity!=null){
						manager = (ConnectivityManager) MainApplication.topActivity
								.getApplicationContext().getSystemService(
										Context.CONNECTIVITY_SERVICE);
					}
				}else{
					networkinfo = manager.getActiveNetworkInfo();
					if (networkinfo == null || !networkinfo.isAvailable()) {
						MyStatus.online = false;
						if(MainApplication.topActivity!=null){
							MainApplication.topActivity.setStatus(1, false);
							MainApplication.topActivity.refreshLine();
						}
					}else{
						MyStatus.online = true;
						if(MainApplication.topActivity!=null){
							MainApplication.topActivity.setStatus(1, true);
							CWTBaseActivity.refreshcount = 100;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			count_checkNet++;
		}
		AppLog.savelog("线程问题：1-网络检查2");




		/**
		 * 定时播放背景音，使得功放保持激活状态，掩饰硬件bug
		 *
		 * 第二次声音规则，准备废弃
		 */
//		if (count_volBg > 20) {
//			if(MainApplication.firstviv){
//				MainApplication.firstviv = false;
//				count_volBg = 18;
////				MCUUtil.selecterVic(2);
//				MCUUtil.setvol(1, "开机预防pop声强制音量1");
//				MCUUtil.hasVic(false);
//			}else{
//				if(mMediaPlayer==null){
//					if(MainApplication.topActivity!=null){
//						mMediaPlayer = MediaPlayer.create(MainApplication.topActivity, R.raw.testbg);
//					}
//					if(mMediaPlayer!=null){
//						AppLog.e("播放背景音001");
//						mMediaPlayer.start();
//						AppLog.e("播放背景音002");
//						count_volBg = 0;
//						new Thread(new Runnable() {
//
//							@Override
//							public void run() {
//								// TODO Auto-generated method stub
//								try {
//									Thread.sleep(5000);
//									MCUUtil.hasVic(true);
//									Thread.sleep(2000);
//									MCUUtil.setvol(6, "初次播放背景空白音后恢复默认音量6");
//								} catch (Exception e) {
//									// TODO: handle exception
//								}
//							}
//						}).start();
//					}
//				}else{
//					mMediaPlayer.start();
//					count_volBg = 0;
//					AppLog.e("播放背景音");
//				}
//			}
//		} else {
//			count_volBg++;
//		}


		//第一次声音规则，已废弃
//		if (count_volBg > 20) {
//			if(firstviv){
////				MCUUtil.hasVic2(false);
//				firstviv = false;
//				count_volBg = 22;
//				MCUUtil.hasVic(false);
//				MCUUtil.hasVic2(false);
//			}else{
//				if(mMediaPlayer==null){
//					if(MainApplication.topActivity!=null){
//						mMediaPlayer = MediaPlayer.create(MainApplication.topActivity, R.raw.testbg);
//					}
//					if(mMediaPlayer!=null){
//						AppLog.e("播放背景音001");
//						mMediaPlayer.start();
//						AppLog.e("播放背景音002");
//						count_volBg = 0;
//						MCUUtil.hasVic(true);
//						MCUUtil.hasVic2(true);
//					}
//				}else{
////					mMediaPlayer.stop();
//					mMediaPlayer.start();
//					count_volBg = 0;
//					AppLog.e("播放背景音");
////					MCUUtil.hasVic(true);
//					if(isfirstVol==1){
////						new Thread(new Runnable() {
////							@Override
////							public void run() {
////								try {
////									Thread.sleep(1000);
//////									MCUUtil.setvol(0);
////									Thread.sleep(1000);
////									MCUUtil.hasVic(true);
////									Thread.sleep(1000);
//////									MCUUtil.selecterVic(2);
////									Thread.sleep(1000);
//////									MCUUtil.setvol(6);
////									MCUUtil.hasVic2(true);
////								} catch (Exception e) {
////									e.printStackTrace();
////								}
////							}
////						}).start();
//						isfirstVol = 2;
//					}
//				}
//			}
//		} else {
//			count_volBg++;
//		}




		if (count_checkLog > 60 * 60) {
			CatchLogUtils.deleteSDcardExpiredLog();
		} else {
			count_checkLog++;
		}

		if (count_checkDvrState > 60) {
			try {
				String url = "http://" + SPConstants.SPV_dvrip_zg + ":6681/get_status?video_lost=&main_rec_mask=";
				OkHttpClient okHttpClient = new OkHttpClient();
				Request request = new Request.Builder()
						.url(url)
						.get()//默认就是GET请求，可以不写
						.build();
				Callback callback = new Callback() {
					@Override
					public void onFailure(Call call, IOException e) {

					}

					@Override
					public void onResponse(Call call, Response response) throws IOException {
						try{
							String s = response.body().string();
							AppLog.e("s= " + s);
							String ss[] = s.split("=");
							if(ss.length<5){
								return;
							}
							for (int i = 0; i < ss.length; i++) {
								AppLog.e("ss= " + ss[i]);
							}
							String recordState = ss[ss.length - 2].substring(0,3);
							AppLog.e("sss=" + recordState);
							CatchLogUtils.saveLog("dvr状态:" + recordState,new Date());
							if ("0xf".equals(recordState)){
								CatchLogUtils.saveLog("dvr状态：正在录像   ",new Date());
								ConstantsState.setStateValue(31,"0");
							}else if ("0x0".equals(recordState)){
								CatchLogUtils.saveLog("dvr状态：停止录像   ",new Date());
								ConstantsState.setStateValue(31,"1");
							}
						}catch(Exception e){
							e.printStackTrace();
						}
					}
				};

				Call call = okHttpClient.newCall(request);
				call.enqueue(callback);
			} catch (Exception e) {
			}finally {
				count_checkDvrState = 0;
			}
		}else{
			count_checkDvrState++;
		}

		if (count_checkMemory > 60){
			String usedMemory = SystemUtils.getUsedPercentValue(MainApplication.topActivity);
			CatchLogUtils.saveLog("内存:" + usedMemory,new Date());
			count_checkMemory = 0;
		}else{
			count_checkMemory++;
		}
		if (count_checkCPU > 60){
			String usedCPU = String.valueOf(SystemUtils.getTotalCpuRate());
			CatchLogUtils.saveLog("CPU:使用率:" + usedCPU,new Date());
			count_checkCPU = 0;
		}else{
			count_checkCPU++;
		}

		if (count_checkCPUTemp> 60){
			String usedCPU = SystemUtils.getCpuTemp();
			CatchLogUtils.saveLog("CPU:温度" + usedCPU,new Date());
			count_checkCPUTemp = 0;
		}else{
			count_checkCPUTemp++;
		}



		/**
		 * 自动读卡
		 */
		if(CardUtil.autoRead&&ActivityWaitQD.isview){
//			 CardUtil.readCard(16*6);
//			 CardUtil.readCardNumber();
//			 CardUtil.sendTsm905Data(0x0020, null);
		}


		AppLog.savelog("线程问题：2-检查计价器选择1");
		/**
		 * 检查计价器选择
		 */
		if(DataUtil.getJJQ()== 0&&!(MainApplication.topActivity instanceof ActivityJJQ)){
			Intent intent2 = new Intent();
			intent2.setClass(MainApplication.getInstance(), ActivityJJQ.class);
			intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			MainApplication.getInstance().startActivity(intent2);
		}
		AppLog.savelog("线程问题：2-检查计价器选择2");

		/**
		 * 口罩检测
		 */
//		if (SPUtils.getParamBoolean(SPConstants.SPK_Mask,true)){
//			if(count_maskCheck>60){
//				AppLog.e("开始口罩检查");
//				Intent intent = new Intent(FloatService.action_camera);
//				intent.putExtra("type", 3);
//				intent.putExtra("w", 640);
//				intent.putExtra("h", 480);
//				MainApplication.topActivity.sendBroadcast(intent);
//				count_maskCheck = 0;
//			}else{
//				count_maskCheck++;
//			}
//		}


		AppLog.savelog("线程问题：3-顶灯校时1");
		/**
		 * 顶灯校时
		 */
		if(count_ddtime>60*10){
			DDUtil.sendDDtime();
			count_ddtime = 0;
		}else{
			count_ddtime++;
		}
		AppLog.savelog("线程问题：3-顶灯校时2");



		AppLog.savelog("线程问题：4-设置dvr参数1");
		/**
		 * 设置dvr参数
		 */
		//AppLog.d(TAG,"线程问题：4-设置dvr参数 count_checkDVR:" + count_checkDVR);
		 if(count_checkDVR>60 * 5){
			 //AppLog.d(TAG,"线程问题：4-设置dvr参数2");
//			 if(count_checkDVR>20){
			 try {
				 String code = DeviceBiz.getDeviceCode();
				 AppLog.d(TAG,"线程问题：4-设置dvr参数2 code:" + code);
				 if(code!=null&&code.length()>2){
					 if(SPUtils.getParamInteger(SPConstants.SPK_dvr, SPConstants.SPV_dvr)==1){
						 AppLog.d(TAG,"线程问题：4-设置dvr参数2 sendSet");
						 DvrService.getInstance().sendSet(code.substring(2), DeviceBiz.getCarNumberSingleLetter());
					 }else{
						 AppLog.d(TAG,"线程问题：4-设置dvr参数2 sendHttpGetSet");
						 DvrService.getInstance().sendHttpGetSet();
						 AppLog.savelog("线程问题：4-设置dvr参数2 sendHttpGetSet");
					 }
				 }
			} catch (Exception e) {
				e.printStackTrace();
			}
			 count_checkDVR = 0;
		 }else{
			 count_checkDVR++;
		 }
		AppLog.savelog("线程问题：4-设置dvr参数2");


		AppLog.savelog("线程问题：5-检查新版本1");
		/**
		 * 检查新版本
		 */
		if(count_vUp>60*20){//---------------------------------------------------------------------------------------------

			//顺便关闭wifi热点
			closeWifiHotspot();
//			 new Thread(new Runnable() {
//				@Override
//				public void run() {
//					try {
//						WifiManager wifiManager = (WifiManager) MainApplication.topActivity.getSystemService(Context.WIFI_SERVICE);
// 						wifiManager.setWifiEnabled(false);
// 						Thread.sleep(5000);
// 						wifiManager.setWifiEnabled(true);
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//				}
//			}).start();


			//顺便检查是否需要修改参数
			try {
				String result = doJsonPost("http://taxi.jpfwpt.com:4657/rest/getVehicleChange/"+DeviceBiz.getCarNumberSingleLetter(), "");
				JSONObject obj = new JSONObject(result);
				int status = obj.getInt("errorcode");
				if (status == 0) {
					JSONArray js = obj.getJSONArray("data");
					for (int i = 0; i < js.length(); i++) {
						obj = js.getJSONObject(i);
						int type = obj.getInt("type");
						String value = obj.getString("value");
						AppLog.e(type+"-----------"+value);
						switch (type) {
							case 1://暂时不处理mac修改
								break;
							case 2://设备ID
								DeviceBiz.setDeviceCode(value);
								break;
							case 3://IP地址
								DeviceBiz.setIp(value);
								break;
							case 4://计价器
								if(value.contains("聚利")){
									DataUtil.saveJJQ(1);
								}else if(value.contains("通用")){
									DataUtil.saveJJQ(2);
								}
								break;
							case 5://DVR
								if(value.contains("通力")){
									SPUtils.setParam(SPConstants.SPK_dvr, 1);
								}else if(value.contains("车务通")){
									SPUtils.setParam(SPConstants.SPK_dvr, 2);
								}
								break;
							case 6://端口
								DeviceBiz.setPort(value);
								break;
							case 7://日志回传
								Log.e("TunerCommon","value:" + value);
								if(!TextUtils.isEmpty(value)){
									if(value.contains("日志回传")){
										//上传日志
										logUpload();
									}
								}

								break;

						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}


			if(!(MainApplication.topActivity instanceof ShowVersionInfo) && Constants.APK_UPDATE){
				doCheckVersionNew();
			}
			count_vUp = 0;
		}else{
			count_vUp++;
		}
		AppLog.savelog("线程问题：5-检查新版本2");

		AppLog.savelog("线程问题：6-检查串口是否重启1");
		/**
		 * 检查串口是否重启
		 */
//		 if(count_232>10){
		if(count_232>2*60){
			doCheck232();
			count_232 = 0;
		}else{
			count_232++;
		}
		AppLog.savelog("线程问题：6-检查串口是否重启2");



		/**
		 * 检查MCU版本
		 */
		if(count_checkMCU>3*60){
			AppLog.savelog("线程问题：7-检查MCU版本1");//DVRV-T19071875=V1812120+
			checkBuglog();
			if(MCUUtil.MCUV!=null&&MCUUtil.MCUV.contains("CWT")){
				SPUtils.setParam("lastNoNullMcuV", MCUUtil.MCUV);
			}
			try {

				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							String url = "http://"+SPConstants.SPV_dvrip_zg+":6681/get_dvr_para?fixPara.appVersion=&fixPara.mcuVersion=";
							HttpEntity httpEntity = HttpUtils.getEntity(url, null, HttpUtils.METHOD_GET);
							InputStream inputStream = HttpUtils.getStream(httpEntity);
							String json = StringParser.parse(inputStream);
							inputStream.close();
							if(json.contains("200")){
								AppLog.e("----------->"+json);
							}else{
								//fixPara.appVersion=T19062570fixPara.mcuVersion=V18121201
								AppLog.e("400----------->"+json);
								json = json.replace("fixPara.appVersion=", "");
								json = json.replace("fixPara.mcuVersion", "");
								DVRV = json;
							}
						} catch (Exception e) {
//					e.printStackTrace();
						}
						AppLog.e("获取DVR版本：DVRV-"+DVRV);


//				 int vcode = MainApplication.topActivity.getPackageManager().getPackageInfo(MainApplication.topActivity.getPackageName(), 0).versionCode;
						int vcode = Constants.localVersion;
						AppLog.e("获取DVR版本：DVRV-"+DVRV+"     lastSendDVRV-"+lastSendDVRV+"     lastSendDVRV-"+lastSendAppV+"     vcode-"+vcode);

						if ((!DVRV.equals(lastSendDVRV)&&!DVRV.equals("null")) || vcode != lastSendAppV) {

							AppLog.e("获取DVR版本：send");

//                if (!MCUUtil.MCUV.equals(lastSendMcuV) || vcode != lastSendAppV) {
//                if (vcode != lastSendAppV) {
							Vinfo info = new Vinfo();
							info.setTermMac(Tools.getMacAddress(1));
							info.setApk(vcode + "");
							info.setMcu(SPUtils.getParamString("lastNoNullMcuV", "--"));
//                    info.setMcu(MCUUtil.MCUV);
							info.setDvr(DVRV + "   提交时间：" + new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒 ").format(new Date()));


							Gson g = new Gson();
							String result = doJsonPost("http://taxi.jpfwpt.com:4657/rest/addMacViersion", g.toJson(info));

							JSONObject obj = null;
							try {
								obj = new JSONObject(result);
							} catch (JSONException e) {
								e.printStackTrace();
							}
							int status = 0;
							try {
								status = obj.getInt("errorcode");
								if (status == 0) {
									lastSendDVRV = DVRV;
									lastSendAppV = vcode;
								}
							} catch (Exception e) {
								e.printStackTrace();
							}

							AppLog.e("获取DVR版本：lastSendDVRV-"+lastSendDVRV+"     lastSendAppV"+lastSendAppV);
						}
					}
				}).start();

			} catch (Exception e) {
				e.printStackTrace();
			}


//			try {
//				int vcode = Constants.localVersion;
//				if(!MCUUtil.MCUV.equals(lastSendMcuV)||vcode!=lastSendAppV){
//					Vinfo info = new Vinfo();
//					info.setTermMac(Tools.getMacAddress(1));
//					info.setApk(vcode+"");
//					info.setMcu(MCUUtil.MCUV);
//					info.setDvr(SPUtils.getParamString("lastNoNullMcuV", "--")+"   提交时间："+new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒 ").format(new Date()));
//
//
//					Gson g = new Gson();
//					String result = doJsonPost("http://taxi.jpfwpt.com:4657/rest/addMacViersion", g.toJson(info));
//					AppLog.d(TAG,"线程问题：7-提交信息到平台addMacViersion："+ result + " info:" + g.toJson(info));
//					JSONObject obj = new JSONObject(result);
//					int status = obj.getInt("errorcode");
//					if (status == 0) {
//						lastSendMcuV = MCUUtil.MCUV;
//						lastSendAppV = vcode;
//					}
//
//				}
//			} catch (Exception e) {
//			}


			if(MCUUtil.MCUV==null||MCUUtil.MCUV.equals("")||!MCUUtil.MCUV.contains("CWT")){
				MCUUtil.checkV();
//				 count_checkMCU = 150;
				count_checkMCU = 0;
			}else{

				SPUtils.setParam("lastNoNullMcuV", MCUUtil.MCUV);

				if(Constants.MCU_CHECK_ENABLE && !MCUUtil.MCUV.endsWith(Constants.MCU_VERSION)){
//					 MainApplication.topActivity.showNormalDialog();
					MCUUtil.mVoiceTool.closeTimer();
					MCUUtil.MCUV = "";
					MCUUtil.UpV();
				}
				count_checkMCU = 0;
			}
			AppLog.savelog("线程问题：7-检查MCU版本2");
		}else{
			count_checkMCU++;
		}

		/**
		 * 提交信息到平台
		 */
		if(count_sendInfo>10*60){
			AppLog.d(TAG,"count_sendInfo MyStatus.center:" + MyStatus.center);
			AppLog.savelog("线程问题：8-提交信息到平台1");
			if(MyStatus.center){
				try {
					String carnumber = DeviceBiz.getCarNumberSingleLetter();
					String code = DeviceBiz.getDeviceCode();
					String mac = Tools.getMacAddress(1);
					AppLog.d(TAG,"count_sendInfo DeviceBiz.getCarNumberCorrection():" + (!DeviceBiz.getCarNumberCorrection()) + " carnumber:" + carnumber + " code:" + code + " mac:" + mac);
					if(carnumber!=null&&carnumber.length()>0
							&&code!=null&&code.length()>0
							&&mac!=null&&mac.length()>0
							&&!DeviceBiz.getCarNumberCorrection()){
						carInfo info = new carInfo();
						info.setLicNum(carnumber);
						info.setTermNum(code);
						info.setTermMac(mac);
						info.setCode(Constants.PROJECT_CODE);
						Gson g = new Gson();
						String result = doJsonPost("http://taxi.jpfwpt.com:4657/rest/saveBindInfo", g.toJson(info));
						AppLog.savelog("线程问题：8-提交信息到平台saveBindInfo："+result);
						AppLog.d(TAG,"count_sendInfo saveBindInfo："+result + " info:" + g.toJson(info));
						result = doJsonPost("http://taxi.jpfwpt.com:4657/rest/saveVehicleBindLog", g.toJson(info));
						AppLog.savelog("线程问题：8-提交信息到平台saveVehicleBindLog："+result + " info:" + g.toJson(info));
						AppLog.d(TAG,"count_sendInfo saveVehicleBindLog："+result + " info:" + g.toJson(info));
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			count_sendInfo = 0;
			AppLog.savelog("线程问题：8-提交信息到平台2");
		}else{
			count_sendInfo++;
		}




		//检查非法app
		if(count_bmd>60*20){
			//顺便处理cwtlogbug
			checkcwtlog("/mnt/sdcard/CWTLOG");
			checkcwtlog("/mnt/sdcard/CWTLog");
			checkcwtlog("/mnt/sdcard/cwtlog");

			//https://mapdownload.autonavi.com/amapauto/apk/autobasic/guanwangV4.0.0.6130_FRSE3276F0.apk
			count_bmd = 0;
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						AppLog.e("检查非法APP");
						AppBiz ab = new AppBiz(MainApplication.topActivity);
						List<AppInfo> apps = ab.queryFilterAppInfo(AppBiz.FILTER_THIRD_APP);
						AppLog.e("检查非法APP-apps.size:"+apps.size());
						boolean ex;
						String pg;
						for (int i = 0; i < apps.size(); i++) {
							ex = false;
							pg = apps.get(i).getPkgName();
							AppLog.e("检查非法APP-PkgName-"+i+":"+pg);
							for (int j = 0; j < ActivityMain.bmd.length; j++) {
								if(pg.equals(ActivityMain.bmd[j])){
									ex = true;
								}
							}
							if(!ex){
								ActivityMain.execCommand("pm","uninstall", pg);
								Thread.sleep(2000);
								AppLog.e("检查非法APP-卸载："+pg);
							}else{
								AppLog.e("检查非法APP-合法");
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}).start();
		}else{
			count_bmd++;
		}


		//AppLog.savelog("线程问题：0-线程结束："+System.currentTimeMillis());

	}



	private void checkcwtlog(String string) {
		// TODO Auto-generated method stub
		File f = new File(string);
		if(f.exists()){
			Tools.delFolder(string);
		}
	}



	//发送JSON字符串 如果成功则返回成功标识。
	public static String doJsonPost(String urlPath, String Json) {
		// HttpClient 6.0被抛弃了
		String result = "";
		BufferedReader reader = null;
		try {
			URL url = new URL(urlPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			// 设置文件类型:
			conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
			// 设置接收类型否则返回415错误
			//conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
			conn.setRequestProperty("accept","application/json");
			// 往服务器里面发送数据
			if (Json != null && !TextUtils.isEmpty(Json)) {
				byte[] writebytes = Json.getBytes();
				// 设置文件长度
				conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
				OutputStream outwritestream = conn.getOutputStream();
				outwritestream.write(Json.getBytes());
				outwritestream.flush();
				outwritestream.close();
				Log.d("hlhupload", "doJsonPost: conn"+conn.getResponseCode());
			}
			if (conn.getResponseCode() == 200) {
				reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				result = reader.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	/**
	 * http://taxi.jpfwpt.com:4657/upload/log/陕AAAAAA_20190527.zip
	 * @param url 上传路径
	 * @param filePath	文件本地全路径
	 * @param fileName	上传文件名称
	 */
	private void uploadFile(String url,String filePath,String fileName){
		Log.d(TAG,"uploadFile start!");
		File file = new File(filePath);
		RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
		RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
				.addFormDataPart("file", fileName , fileBody)
				.build();
		Request request = new Request.Builder().url(url)
				.post(requestBody)
				.build();
		OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
		OkHttpClient okHttpClient = httpBuilder
				.connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
				.writeTimeout(150, java.util.concurrent.TimeUnit.SECONDS)//150秒
				.build();
		//Response response = okHttpClient.newCall(request).execute();
		okHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onResponse(Call arg0, Response response) throws IOException {
				// TODO Auto-generated method stub
				if(response != null){
					String string = response.body().string();
					Log.d(TAG,"uploadFile response " + string);
					AppLog.savelog("日志回传 response ----->" + string + System.currentTimeMillis());
					FileOper.del(new File(getCompressFilePath()));
				}
			}

			@Override
			public void onFailure(Call arg0, IOException e) {
				// TODO Auto-generated method stub
				Log.d(TAG,"uploadFile onFailure e.getMessage():" + e.getMessage());
				AppLog.savelog("日志回传 response ----->" + e.getMessage() + System.currentTimeMillis());
			}
		});
	}

	private String getCompressFilePath(){
		return "/mnt/sdcard/compress.zip";
	}

	private String getCompressPath(){
		return "/mnt/sdcard/导航终端日志文件/";
	}

	private String getUploadPath(){
		return "http://taxi.jpfwpt.com:4657/rest/imageup/" + DeviceBiz.getCarNumber();
	}

	private String getFileName(String path){
		if(!TextUtils.isEmpty(path)){
			int index = path.lastIndexOf("/");
			if(index > -1){
				return path.substring(index + 1);
			}
		}
		return path;
	}

	/**
	 * 文件压缩
	 * @param ompressFile
	 * @param ompressPath
	 */
	private void zipPath(String ompressFile,String ompressPath){
		Log.d("TimerCommon", "zipPath ompressFile:" + ompressFile + " ompressPath:" + ompressPath);
		if(!TextUtils.isEmpty(ompressPath)){
			File file = new File(ompressPath);
			String[] files = file.list();
			if(files != null && files.length > 0){
				String[] filePaths = new String[files.length];
				for(int i = 0 ; i < files.length ; i ++){
					filePaths[i] = ompressPath + files[i];
				}
				Log.d(TAG,"压缩日志开始"+System.currentTimeMillis());
				AppLog.savelog("压缩日志开始："+System.currentTimeMillis());
				new Zipper().compress(ompressFile,filePaths);
				Log.d(TAG,"压缩完成!："+System.currentTimeMillis());
				AppLog.savelog("压缩完成!："+System.currentTimeMillis());
			}
		}
	}

	public void logUpload(){
		new Thread(new Runnable() {

			@Override
			public void run() {
				try{
					// TODO Auto-generated method stub
					FileOper.del(new File(getCompressFilePath()));
					zipPath(getCompressFilePath(),getCompressPath());
					uploadFile(getUploadPath(), getCompressFilePath(), getFileName(getCompressFilePath()));

				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}).start();
	}

	long lastcheckBuglogtime = 0;
	private void checkBuglog() {
		if(System.currentTimeMillis()-lastcheckBuglogtime<10*60*1000){
			return;
		}else{
			lastcheckBuglogtime = System.currentTimeMillis();
		}
		File file = new File("/mnt/sdcard/");
		File[] fs = file.listFiles();
		ArrayList<String> buglist = new ArrayList<>();
		for (int i = 0; i < fs.length; i++) {
			if(fs[i].getAbsolutePath().contains("Buglog")){
				buglist.add(fs[i].getAbsolutePath());
			}
		}
		if(buglist.size()>0){
			for (int i = 0; i < buglist.size(); i++) {
				AppLog.e(buglist.get(i));
				try {
					file = new File(buglist.get(i));
					int length=(int)file.length();
					byte[] buff=new byte[length];
					FileInputStream fin=new FileInputStream(file);
					fin.read(buff);
					fin.close();
					String str = new String(buff);

					AppLog.savelog("上传bug日志\n"+str);

					loginfo info = new loginfo();
					info.setLicNum(DeviceBiz.getCarNumber());
					info.setTermNum(DeviceBiz.getDeviceCode());
					info.setTermMac(Tools.getMacAddress(1));
					info.setType(1);
					info.setLogs(str);

					Gson g = new Gson();
					String result = doJsonPost("http://taxi.jpfwpt.com:4657/rest/addLog", g.toJson(info));
					AppLog.e("-------------");
					AppLog.e(result);
					AppLog.e("-------------");
					try {
						JSONObject obj = new JSONObject(result);
						int status = obj.getInt("errorcode");
						if (status == 0) {
							file.delete();
						}
					} catch (Exception e) {
//						 e.printStackTrace();
					}

				} catch (Exception e) {
//					e.printStackTrace();
				}

			}
		}
	}

	public static  void sendLog(final int type, final String str) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					loginfo info = new loginfo();
					info.setLicNum(DeviceBiz.getCarNumber());
					info.setTermNum(DeviceBiz.getDeviceCode());
					info.setTermMac(Tools.getMacAddress(1));
					info.setType(type);
					info.setLogs(str);

					Gson g = new Gson();
					String result = doJsonPost("http://taxi.jpfwpt.com:4657/rest/addLog", g.toJson(info));
					AppLog.e("-------------");
					AppLog.e(result);
					AppLog.e("-------------");
//			try {
//				JSONObject obj = new JSONObject(result);
//				int status = obj.getInt("errorcode");
//				if (status == 0) {
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}



	public void doCheck232(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				SerialPortService.getInstance().sendSerialData6(MeterEncoder.queryMeterState());
				try {Thread.sleep(3000);} catch (Exception e) {}
				if(System.currentTimeMillis()-ActivityPower.jjqtime>3000){

					MCUUtil.reH = false;

//					TTsFunction.speakText("重置PC7");
//					VolumeControl.playSound();
//					try {Thread.sleep(1000);} catch (Exception e) {}
					try {Thread.sleep(200);} catch (Exception e) {}

					AppLog.e("计价器串口检测断开，尝试复位PC7");
					MCUUtil.setIO(5, false);
					try {Thread.sleep(100);} catch (Exception e) {}
					MCUUtil.setIO(5, true);

					try {Thread.sleep(1000);} catch (Exception e) {}
					MCUUtil.reH = true;
				}
			}
		}).start();
	}



	/**
	 * 后台检查更新
	 * 4658端口有排队机制,如果下载失败,有可能是服务器空间不足
	 * @param
	 * @return
	 */


	public void doCheckVersionNew() {
		boolean isConnected = ToastUtils.isConnect(MainApplication.getInstance().getApplicationContext());
		if (isConnected) {
			new AsyncTask<String, Void, Void>() {
				@Override
				protected Void doInBackground(String... params) {
					try {
						String url = "http://taxi.jpfwpt.com:4657/rest/version";
						OkHttpClient okHttpClient = new OkHttpClient();
						String jsonBody = VersionBiz.getVersionJsonBody();
						Log.d(TAG, "checkVersion jsonBody:" + jsonBody);
						if (!TextUtils.isEmpty(jsonBody)) {
							RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);
							Request request = new Request.Builder()
									.url(url)//请求的url
									.post(requestBody)
									.build();
							try {
								Response response = okHttpClient.newCall(request).execute();
								String string = response.body().string();
								Log.e(TAG, "response ----->" + string);
								JSONObject obj = new JSONObject(string);
								int status = obj.getInt("errorcode");
								if (status == 0) {
									obj = obj.getJSONObject("data");
									final int v = obj.getInt("version");
									int locVersion = Constants.localVersion;//
									if (v != locVersion ) {

										File file = new File(Environment.getExternalStorageDirectory(), "新版本-"+v+".apk");
										if(file.exists()&&file.length()>7*1024*1024){
											if(MainApplication.topActivity!=null){
												MainApplication.topActivity.showLocaUpdata(file.getAbsolutePath());
											}
										}else{
											//http://taxi.jpfwpt.com:4658/apk/9/wnjp_e5/1
											String downpath = "http://taxi.jpfwpt.com:4658/apk/" + v + "/"+ Constants.PROJECT_CODE +"/1";
											Request request2 = new Request.Builder().url(downpath).build();
											new OkHttpClient().newCall(request2).enqueue(new Callback() {
												@Override
												public void onFailure(Call call, IOException e) {
													// 下载失败
													e.printStackTrace();
													AppLog.e("下载失败");
												}

												@Override
												public void onResponse(Call call, Response response) throws IOException {
													File file = new File(Environment.getExternalStorageDirectory(), "新版本-"+v+".apk");
													try {
														InputStream is = response.body().byteStream();// 从服务器得到输入流对象
														BufferedInputStream bis = new BufferedInputStream(is);

														FileOutputStream fos = new FileOutputStream(file);

														byte[] buffer = new byte[1024];
														int len;

														while ((len = bis.read(buffer)) != -1) {
															fos.write(buffer, 0, len);
															AppLog.e("后台下载中");
														}
														fos.flush();
														fos.close();
														bis.close();
														is.close();
														if(file.length()>1024*1024){
															if(MainApplication.topActivity!=null){
																MainApplication.topActivity.showLocaUpdata(file.getAbsolutePath());
															}
														}else{
															boolean dele = file.delete();
															AppLog.e("非apk文件删除："+dele);
														}
													} catch (Exception e) {
														e.printStackTrace();
														if(file.exists()){
															boolean dele = file.delete();
															AppLog.e("下载出错，错误文件删除："+dele);
														}else{
															AppLog.e("下载出错，错误文件不存在");
														}
													}

												}

											});
										}
									}
								}

							} catch (IOException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}else{
							Log.e(TAG, "上传 response -----> getVersionJsonBody is null");
						}
					} catch (Exception e) {
						e.printStackTrace();
						AppLog.e(ExceptionUtil.getInfo(e), e);
					}
					return null;
				}

			}.execute();
		}
	}

	/**
	 * 关闭WiFi热点
	 */
	public void closeWifiHotspot() {
		try {
			WifiManager wifiManager = (WifiManager) MainApplication.topActivity.getSystemService(Context.WIFI_SERVICE);
			Method method = wifiManager.getClass().getMethod("getWifiApConfiguration");
			method.setAccessible(true);
			WifiConfiguration config = (WifiConfiguration) method.invoke(wifiManager);
			Method method2 = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
			method2.invoke(wifiManager, config, false);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}






}
